package com.test.mq;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AceMQProducer {
public static final Logger LOGGER=LoggerFactory.getLogger(AceMQProducer.class);
private DefaultMQProducer producer;
private String groupName="orderProducerGroup";
private String namesrvAddr="192.168.0.105:9876;192.168.0.106:9876";
private int maxMessageSize=1024*1024*4;
private int sendMsgTimeout=10000;


public void setGroupName(String groupName) {
	this.groupName = groupName;
}

public void setNamesrvAddr(String namesrvAddr) {
	this.namesrvAddr = namesrvAddr;
}

public void setMaxMessageSize(int maxMessageSize) {
	this.maxMessageSize = maxMessageSize;
}

public void setSendMsgTimeout(int sendMsgTimeout) {
	this.sendMsgTimeout = sendMsgTimeout;
}

public AceMQProducer() throws AceMQException{
	if(StringUtils.isBlank(this.groupName)){
		throw new AceMQException("groupName is blank!");
	}
	if(StringUtils.isBlank(this.namesrvAddr)){
		throw new AceMQException("namesrvAddr is blank!");
	}
	this.producer=new DefaultMQProducer(this.groupName);
	this.producer.setNamesrvAddr(namesrvAddr);
	this.producer.setMaxMessageSize(maxMessageSize);
	this.producer.setSendMsgTimeout(sendMsgTimeout);
	try {
		this.producer.start();
		LOGGER.info(String.format("producer is start! groupName:{%s},namesrvAddr:{%s}", this.groupName,this.namesrvAddr));
	} catch (MQClientException e) {
		LOGGER.error(String.format("producer error! groupName:{%s},namesrvAddr:{%s}", this.groupName,this.namesrvAddr,e));
		throw new AceMQException(e);
	}
}

private SendResult sendMessage(String topic,String tags,String keys,String messageText) throws AceMQException{
	if(StringUtils.isBlank(topic)){
		throw new AceMQException("topic is blank!");
	}
	if(StringUtils.isBlank(messageText)){
		throw new AceMQException("messageText is blank!");
	}
	Message message=new Message(topic,tags,keys,messageText.getBytes());
	try {
		SendResult sendResult=this.producer.send(message);
		return sendResult;
	} catch (Exception e) {
		LOGGER.error("send message error:",e.getMessage());
		throw new AceMQException(e);
	}
	
	
}

public static void main(String[] args) throws AceMQException {
	new AceMQProducer().sendMessage("orderTopic", "cancel", "*", "xxxxxxx");
}
}
